package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;
import org.csu.mypetstore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

//该类完成一些基本的用户服务，包括添加商品到购物车，生成订单，查看用户日志等
public class UserServiceServlet extends BaseServlet{
    private static final long serialVersionUID = -4038684592582714235L;

    //购物车相关
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    public static final String LOG_IN = "/WEB-INF/jsp/account/SignonForm.jsp";

    private static final String MAIN = "/WEB-INF/jsp/catalog/Main.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    public static final String CART = "/WEB-INF/jsp/cart/Cart.jsp";

    //订单相关
    private static final String CHECK_OUT = "/WEB-INF/jsp/cart/Checkout.jsp";

    public static final String NEW_ORDER_FORM = "/WEB-INF/jsp/order/NewOrderForm.jsp";

    public static final String SHIPPING_FORM = "/WEB-INF/jsp/order/ShippingForm.jsp";

    public static final String VIEW_ORDER = "/WEB-INF/jsp/order/ViewOrder.jsp";

    public static final String CONFIRM_ORDER = "/WEB-INF/jsp/order/ConfirmOrder.jsp";

    public static final String MY_ORDERS = "/WEB-INF/jsp/order/ListOrders.jsp";

    //日志相关
    private static final String VIEW_LOG = "/WEB-INF/jsp/log/UserLog.jsp";

    //浏览购物车
    protected void viewCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //一些需要的变量
        CartService cartService;

        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");

        //查看是否登录，如果登录了
        if(account != null){
            Cart cart = (Cart) session.getAttribute("cart");
            if(cart == null){
                cartService = new CartService();
                cart = cartService.getCartByAccount(account);
                session.setAttribute("cart",cart);
            }
            req.getRequestDispatcher(VIEW_CART).forward(req,resp);
        }
        //如果没有登录
        else{
            req.getRequestDispatcher(LOG_IN).forward(req,resp);
        }
    }

    //添加到购物车
    protected void addItemToCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //一些需要的变量
        String workingItemId;
        CatalogService catalogService;
        CartService cartService;
        LogService logService;
        Cart cart;

        workingItemId = req.getParameter("workingItemId");

        HttpSession session = req.getSession();

        Account account = (Account)session.getAttribute("account");

        //判断用户是否已经登录了，如果已经登录
        if(account != null){
            //首先添加日志
            addLog(workingItemId,account);

            //正常添加至购物车
            if(workingItemId != null){
                cart = (Cart) session.getAttribute("cart");
                //如果session中还没有cart
                if(cart == null){
                    cartService = new CartService();
                    cart = cartService.getCartByAccount(account);
                }
                //如果购物车中已经有该商品了，则根据itemid和username找到这条商品，并将其数量+1
                if(cart != null && cart.containsItemId(workingItemId)){
                    //在数据库中将物品的数量+1
                    catalogService = new CatalogService();
                    cartService = new CartService();
                    boolean isInStock = catalogService.isItemInStock(workingItemId);
                    Item item = catalogService.getItem(workingItemId);
                    CartItem cartItem = new CartItem();
                    cartItem.setItemId(item.getItemId());
                    cartItem.setBuyerName(account.getUsername());
                    cartService.increaseCartItemQuantity(cartItem);
                }
                //如果购物车中没有该商品，插入一个
                else{
                    catalogService = new CatalogService();
                    cartService = new CartService();
                    boolean isInStock = catalogService.isItemInStock(workingItemId);
                    Item item = catalogService.getItem(workingItemId);
                    //在数据库中插入新的物品
                    CartItem cartItem = CartService.itemToCartItem(item,isInStock,1,account.getUsername());
                    cartService.insertItem(cartItem);
                }
                //重新从数据库获取新的cart
                cart = cartService.getCartByAccount(account);
                session.setAttribute("cart",cart);
                //这里使用请求重定向，是为了防止刷新购物车界面后，再次访问addItemToCart，导致商品数量增加
                resp.sendRedirect("service?action=viewCart");
            }
            //返回购物车
            else{
                req.getRequestDispatcher(VIEW_CART).forward(req,resp);
            }
        }
        //没有登录
        else{
            req.getRequestDispatcher(LOG_IN).forward(req,resp);
        }
    }

    //添加一条添加进购物车的记录
    public void addLog(String itemid,Account account){
        //需要的一些变量
        CatalogService catalogService;
        LogService logService;

        catalogService = new CatalogService();
        Item item = catalogService.getItem(itemid);
        Product product = catalogService.getProduct(item.getProductId());

        //创建一个addToCartLog
        AddToCartLog addToCartLog = new AddToCartLog();
        addToCartLog.setUsername(account.getUsername());
        addToCartLog.setItemId(item.getItemId());
        addToCartLog.setDescn(item.getAttr1() + " " + product.getName());
        addToCartLog.setListPrice(item.getListPrice());
        addToCartLog.setDate(new Date());
        addToCartLog.setCount(1);

        //准备工作
        logService = new LogService();
        UserLog userLog = logService.getUserLog(account.getUsername());
        //如果说已经有这条浏览记录了，更新记录
        if(userLog.containsCartLog(addToCartLog)){
            logService.updateCartLog(account.getUsername(),addToCartLog.getItemId());
        }
        //没有
        else{
            logService.insertAddToCartLog(addToCartLog);
        }
    }

    //从购物车中移除
//    protected void removeItemFromCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
//        //需要的一些变量
//        String workingItemId;
//        CartService cartService;
//        Cart cart;
//
//        workingItemId = req.getParameter("cartItem");
//
//        HttpSession session = req.getSession();
//
//        Account account = (Account) session.getAttribute("account");
//        //如果用户已经登录
//        if (account != null){
//            cart = (Cart)session.getAttribute("cart");
//
//            //从session中删除这个cartItem，顺带获取
//            CartItem cartItem = cart.removeItemById(workingItemId);
//
//            if(cartItem == null){
//                session.setAttribute("message","Attempt to remove null item from cart!");
//                req.getRequestDispatcher(ERROR).forward(req,resp);
//            }else{
//                //从数据库中删除cartItem
//                cartService = new CartService();
//                cartService.removeCartItem(cartItem);
//                req.getRequestDispatcher(VIEW_CART).forward(req,resp);
//            }
//        }
//        //如果用户没有登录，返回主界面
//        else{
//            req.getRequestDispatcher(MAIN).forward(req,resp);
//        }
//    }

    //ajax从购物车中移除
    protected void ajaxRemoveItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //需要的一些变量
        String workingItemId;
        CartService cartService;
        Cart cart;

        workingItemId = req.getParameter("itemId");

        HttpSession session = req.getSession();

        Account account = (Account) session.getAttribute("account");
        //如果用户已经登录
        if (account != null){
            cart = (Cart)session.getAttribute("cart");

            //从session中删除这个cartItem，顺带获取
            CartItem cartItem = cart.removeItemById(workingItemId);

            if(cartItem == null){
                session.setAttribute("message","Attempt to remove null item from cart!");
                req.getRequestDispatcher(ERROR).forward(req,resp);
            }else{
                //从数据库中删除cartItem
                cartService = new CartService();
                cartService.removeCartItem(cartItem);
                req.getRequestDispatcher(VIEW_CART).forward(req,resp);
            }
        }
        //如果用户没有登录，返回主界面
        else{
            req.getRequestDispatcher(MAIN).forward(req,resp);
        }
    }

    //ajax更新购物车中某一商品的数量
    protected void ajaxUpdateQuantity(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //需要的一些变量
        CartService cartService;
        HttpSession session = req.getSession();

        //判断用户是否登录
        Account account = (Account) session.getAttribute("account");
        if(account != null){
            cartService = new CartService();

            //首先需要知道购物车中都有哪些itemid
            Cart cart = (Cart)session.getAttribute("cart");

            //更新数据库中的cart
            CartItem cartItem = new CartItem();
            cartItem.setQuantity(Integer.valueOf(req.getParameter("quantity")));
            cartItem.setBuyerName(account.getUsername());
            cartItem.setItemId(req.getParameter("itemId"));
            cartService.updateCartItemQuantity(cartItem);

            //更新session中的cart
            session.setAttribute("cart",cartService.getCartByAccount(account));
            req.getRequestDispatcher(CART).forward(req,resp);
        }
        //没有登录
        else{
            req.getRequestDispatcher(LOG_IN).forward(req,resp);
        }
    }

    //结算
    protected void checkOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getRequestDispatcher(CHECK_OUT).forward(req,resp);
    }

    //newOrderForm
    protected void newOrderForm(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getRequestDispatcher(NEW_ORDER_FORM).forward(req,resp);
    }

    //生成订单（订单加入数据库，清除数据库和session中的购物车信息）
    protected void generateOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //需要的一些变量
        Order order;
        CartService cartService;
        OrderService orderService;

        HttpSession session = req.getSession();
        order = new Order();

        order.setCardType(req.getParameter("order.cardType"));
        order.setCreditCard(req.getParameter("order.creditCard"));
        order.setExpiryDate(req.getParameter("order.expiryDate"));

        order.setBillToFirstName(req.getParameter("order.billToFirstName"));
        order.setBillToLastName(req.getParameter("order.billToLastName"));
        order.setBillAddress1(req.getParameter("order.billAddress1"));
        order.setBillAddress2(req.getParameter("order.billAddress2"));
        order.setBillCity(req.getParameter("order.billCity"));
        order.setBillState(req.getParameter("order.billState"));
        order.setBillZip(req.getParameter("order.billZip"));
        order.setBillCountry(req.getParameter("order.billCountry"));

        if(Boolean.valueOf(req.getParameter("shippingAddressRequired"))){
            order.setShipToFirstName(req.getParameter("order.shipToFirstName"));
            order.setShipToLastName(req.getParameter("order.shipToLastName"));
            order.setShipAddress1(req.getParameter("order.shipAddress1"));
            order.setShipAddress2(req.getParameter("order.shipAddress2"));
            order.setShipCity(req.getParameter("order.shipCity"));
            order.setShipState(req.getParameter("order.shipState"));
            order.setShipZip(req.getParameter("order.shipZip"));
            order.setShipCountry(req.getParameter("order.shipCountry"));
        }else{
            order.setShipToFirstName(req.getParameter("order.billToFirstName"));
            order.setShipToLastName(req.getParameter("order.billToLastName"));
            order.setShipAddress1(req.getParameter("order.billAddress1"));
            order.setShipAddress2(req.getParameter("order.billAddress2"));
            order.setShipCity(req.getParameter("order.billCity"));
            order.setShipState(req.getParameter("order.billState"));
            order.setShipZip(req.getParameter("order.billZip"));
            order.setShipCountry(req.getParameter("order.billCountry"));
        }

        order.setUsername(((Account)session.getAttribute("account")).getUsername());
        order.setTotalPrice(((Cart)session.getAttribute("cart")).getSubTotal());
        order.setOrderDate(new Date());
        order.setCartItems(((Cart)session.getAttribute("cart")).getCartItemList());

        order.setCourier("UPS");
        order.setStatus("P");

        //把购物车清空(数据库和session都清空)
        cartService = new CartService();
        cartService.clearCart((Account)session.getAttribute("account"));
        session.removeAttribute("cart");
        //把订单插入数据库
        orderService = new OrderService();
        order.setOrderId(orderService.getNextId("ordernum"));
        orderService.insertOrder(order);

        session.setAttribute("order",order);

        req.getRequestDispatcher(VIEW_ORDER).forward(req,resp);
    }

    //确认订单
    protected void confirmOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //需要的一些变量
        Order order;

        HttpSession session = req.getSession();
        order = new Order();

        Account account = (Account) session.getAttribute("account");

        order.setOrderId(new Random().nextInt());
        order.setOrderDate(new Date());

        order.setBillToFirstName(account.getFirstName());
        order.setBillToLastName(account.getLastName());
        order.setBillAddress1(account.getAddress1());
        order.setBillAddress2(account.getAddress2());
        order.setBillCity(account.getCity());
        order.setBillState(account.getState());
        order.setBillZip(account.getZip());
        order.setBillCountry(account.getCountry());

        order.setShipAddress1(account.getAddress1());
        order.setShipAddress2(account.getAddress2());
        order.setShipToFirstName(account.getFirstName());
        order.setShipToLastName(account.getLastName());
        order.setShipCity(account.getCity());
        order.setShipState(account.getState());
        order.setShipZip(account.getZip());
        order.setShipCountry(account.getCountry());

        session.setAttribute("order",order);
        req.getRequestDispatcher(CONFIRM_ORDER).forward(req,resp);
    }

    //填写订单的信用卡等信息
    protected void newOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getRequestDispatcher(NEW_ORDER_FORM).forward(req,resp);
    }

    //查询订单记录
    protected void getOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session = req.getSession();
        Account account = (Account)session.getAttribute("account");
        OrderService orderService = new OrderService();
        List<Order> orders = orderService.getOrdersByUsername(account.getUsername());

        session.setAttribute("orderList",orders);

        req.getRequestDispatcher(MY_ORDERS).forward(req,resp);
    }

    //用户浏览自己的日志
    protected void viewLog(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //一些需要的变量
        LogService logService = new LogService();

        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        //如果用户已经登录
        if(account != null){
            session.setAttribute("userLog",logService.getUserLog(account.getUsername()));
            req.getRequestDispatcher(VIEW_LOG).forward(req,resp);
        }
        else{
            req.getRequestDispatcher(MAIN).forward(req,resp);
        }
    }
}
